#!/usr/bin/env node
const fs = require("fs");
const bzipConfig = require("./.bzip.config.js");

const PACKAGE_JSON_PATH = bzipConfig.packageUrl;
const CONFIGNAME = "bzip.config.json";

async function readPackageJson() {
  const json = await fs.promises.readFile(PACKAGE_JSON_PATH, "utf8");
  return JSON.parse(json);
}

async function updatePackageJson(packageJson) {
  try {
    await fs.promises.writeFile(
      PACKAGE_JSON_PATH,
      JSON.stringify(packageJson, null, 2)
    );
    console.log("打包命令初始化成功");
  } catch (error) {
    console.error("打包命令初始化成功:", error);
  }
}

function generateConfig() {
  const config = {
    name: "bzip",
    host: "111.222.333.444",
    port: "22",
    username: "Admin",
    password: "xxxyyyzzz111222333444",
    remoteFolderPath: "c:/test/dist",
  };

  fs.writeFileSync(CONFIGNAME, JSON.stringify(config, null, 2));
}

async function main() {
  const command = "bzip && npm run build && bzip-dist && bzip-open";

  try {
    const packageContent = await readPackageJson();
    if (
      !packageContent.scripts.bzip ||
      packageContent.scripts.bzip !== command
    ) {
      packageContent.scripts.bzip = command;
      await updatePackageJson(packageContent);
    }

    if (!fs.existsSync(bzipConfig.versionLineUrl)) {
      const versionLineContent = {};
      fs.writeFileSync(
        bzipConfig.versionLineUrl,
        JSON.stringify(versionLineContent, null, 2)
      );
    }

    if (!fs.existsSync(bzipConfig.manifestUrl)) {
      const manifestContent = {
        versionName: "",
        timestamp: "",
        versionMsg: "",
      };
      fs.writeFileSync(
        bzipConfig.manifestUrl,
        JSON.stringify(manifestContent, null, 2)
      );
    }

    generateConfig();
  } catch (err) {
    console.log("bzip插件初始化失败", err);
  }
}

main().then((r) => {
  console.log("bzip插件初始化成功");
});
